package 基础语法.网络编程;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TCP_learn {
    public static void main(String[] args) {
        Thread senThread = new Thread() {
            @Override
            public void run() {
                try {
                    sendData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        Thread receiveThread = new Thread() {
            @Override
            public void run() {
                try {
                    receiveData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        receiveThread.start();// 必须先启动
        //senThread.setPriority(100000);
        senThread.start();
       

    }

    static void sendData() throws Exception {
        // 1.
        // 在创建对象是会尝试连接服务器，如果连接不上，代码报错
        Socket socket = new Socket("127.0.0.1", 8080);

        // 2.从连接中获取输出流
        OutputStream os = socket.getOutputStream();// SocketOutputStream
        os.write("你好".getBytes());
        os.close();
        socket.close();

    }

    static void receiveData() throws Exception {
        // 1.
        ServerSocket serverSocket = new ServerSocket(8080);// 端口保持与发送端一致
        // 2.监听客户端的连接
        Socket socket = serverSocket.accept();

        // 3.从连接通道中获取输入流读取数据
        InputStream inputStream = socket.getInputStream();// SocketInputStream

         int b;
        // while ((b = inputStream.read()) != -1) {
        // System.out.println((char) b);//中文乱码
        // }

        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);// 转换流
        // while ((b=inputStreamReader.read())!=-1) {
        // System.out.println((char)b);

        // }
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);// 包装流
        // while((b=bufferedReader.read())!=-1){
        //     System.out.println((char)b);
        // }

        System.out.println(bufferedReader.readLine());
        socket.close();
        bufferedReader.close();

    }

}
